package rpc.log;

import java.util.Objects;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rpc.core.FlowReq;
import rpc.core.FlowRes;
import rpc.trace.Trace;
import rpc.trace.TraceContext;
import rpc.utils.ExceptionUtils;

public class LogFormatManager {

  private static final Logger logger = LoggerFactory.getLogger(LogFormatManager.class);
  private static LogFormatter logFormatter;

  public static LogFormatter getLogFormatter() {
    return logFormatter;
  }

  public static void setLogFormatter(LogFormatter logFormatter) {
    LogFormatManager.logFormatter = logFormatter;
  }

  public static void init() {
    if (Objects.isNull(logFormatter)) {
      logFormatter = new SimpleLogFormatter();
    }
  }


  public static void logger(String currFlowName, FlowReq req, FlowRes res) {
    try {
      LogFormatter logFormatter = LogFormatManager.getLogFormatter();
      TraceContext traceContext = Trace.get();
      LoggerFactory.getLogger("rpc.server." + currFlowName).info("{},   {},   {},   {},   {},   {}", "127.0.0.12", currFlowName, traceContext.getTraceId(),
          res.retCode(), logFormatter.toLogStr(req), logFormatter.toLogStr(res));
    } catch (Exception e) {
      logger.error("exception:{} stackTrace:{}", e.getMessage(), ExceptionUtils.getTrace(e));
    }
  }
}
